'use strict';
const {
  Model
} = require('sequelize');
const moment = require("moment")
moment.locale('zh-cn')
module.exports = (sequelize, DataTypes) => {
  class Comment extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here

      models.Comment.belongsTo(models.Comment, {
        as: 'parent',
        foreignKey: 'parentId'
      })
      models.Comment.hasMany(models.Comment, {
        as: 'replies',
        foreignKey: 'parentId'
      })
      models.Comment.belongsTo(models.Comment, {
        as: 'root',
        foreignKey: 'rootId'
      })
      models.Comment.belongsTo(models.Post, {as: 'post'})
      models.Comment.belongsTo(models.User, {as: 'user'})
    }
  }
  Comment.init({
    content: DataTypes.STRING,
    userId: DataTypes.INTEGER,
    postId: DataTypes.INTEGER,
    parentId: DataTypes.INTEGER,
    rootId: {
      type: DataTypes.INTEGER,
    },
    level: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: {msg: '评论层级填写'},
        notEmpty: {msg: '评论层级不能为空'},
        isIn: {args: [[1, 2, 3]], msg: '评论层级必须是：一级：1  二级： 2  二级的二级：3'}
      }
    },
    createdAt: {
      type: DataTypes.DATE,
      get() {
        return moment(this.getDataValue('createdAt')).format("LL")
      }
    },
    updatedAt: {
      type: DataTypes.DATE,
      get() {
        return moment(this.getDataValue('updatedAt')).format("LL")
      }
    }
  }, {
    sequelize,
    modelName: 'Comment',
  });
  return Comment;
};